/**
 * Copyright (c) 2016-2100 yunclouds
 */
package com.yunqian.web;

import com.yunqian.redot.constant.Operation;
import com.yunqian.redot.constant.OperationMenus;
import com.yunqian.redot.constant.OrderStatus;
import com.yunqian.redot.constant.RefundStatus;
import com.yunqian.redot.domain.CoursesOrder;
import com.yunqian.redot.domain.TicketOrder;
import com.yunqian.redot.domain.TicketOrderDetails;
import com.yunqian.redot.domain.dto.TicketOrderDetailsDto;
import com.yunqian.redot.service.OperationLogService;
import com.yunqian.redot.service.TicketOrderDetailsService;
import com.yunqian.redot.service.TicketOrderService;
import com.yunqian.redot.service.TicketService;
import com.yunqian.util.bean.BeanUtil;
import com.yunqian.util.poi.PoiExcelExport;
import com.yunqian.util.poi.ServletUtil;
import com.yunqian.util.validate.Validator;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Describe: 客户门票订单记录控制器
 *
 * @author zsy
 * 2018-09-29 15:55:07
 */
@Log4j2
@Controller
@RequestMapping("/api/ticketOrder")
public class TicketOrderController {

    @Autowired
    private TicketOrderDetailsService ticketOrderDetailsService;
    @Autowired
    private TicketOrderService ticketOrderService;
    @Autowired
    private TicketService ticketService;
    @Autowired
    private OperationLogService operationLogService;

    /**
     * 获取分页
     *
     * @param params
     * @return
     */
    @ResponseBody
    @PostMapping("/pagination")
    public Page<TicketOrderDetails> pagination(@RequestBody Map<String, Object> params) {
        return ticketOrderDetailsService.pagination(params);
    }

    /**
     * 退款审核
     * @param id
     * @param params
     */
    @ResponseBody
    @PostMapping("/refund/audit/{id}")
    public void audit(@PathVariable("id") Long id, @RequestBody Map<String,Object> params) {
        // 3-同意退款  4-拒绝退款
        Integer status = Integer.valueOf(params.get("status").toString());
        TicketOrder order = ticketOrderService.getById(id);
        order.setAuditTime(new Date()); // 审核时间
        // 订单状态为已取票
        if(Validator.equals(order.getStatus(),OrderStatus.HAVE_THE_TICKETS.getCode())){
            if(Validator.equals(status, RefundStatus.SUCCESS.getCode())){
                // 审核通过
                ticketOrderService.refund(order);
            }else {
                order.setRefundStatus(RefundStatus.FAIL.getCode());
                ticketOrderService.update(order);
            }
        }
    }

    /**
     * 退款详情
     * @param id
     */
    @ResponseBody
    @GetMapping("/refund/info/{id}")
    public Map<String,Object> info(@PathVariable("id") Long id) {
        Map<String,Object> map = new HashMap<>(16);
        TicketOrder order = ticketOrderService.getById(id);
        map.put("refundReason", order.getRefundReason()); // 退款原因
        map.put("applyTime", order.getApplyTime()); // 申请时间
        return map;
    }

    /**
     * 导出excel
     *
     * @param req
     * @param resp
     */
    @RequestMapping("/export")
    public void export(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
        operationLogService.save(OperationMenus.TICKET_ORDER, Operation.EXPORT, Long.valueOf(id));
        String orderNo = req.getParameter("orderNo");
        String phone = req.getParameter("phone");
        String beginTime = req.getParameter("beginTime");
        String endTime = req.getParameter("endTime");
        if (Validator.isNull(beginTime)) {
            beginTime = "2018-01-01 00:00:00";
        }
        if (Validator.isNull(endTime)) {
            endTime = "2050-12-30 23:59:59";
        }
        // 根据时间范围搜索数据
        List<TicketOrderDetails> list = ticketOrderDetailsService.getByOrderNoAndPhoneAndRangeTime(orderNo, phone, beginTime, endTime);
        List<TicketOrderDetailsDto> copyList = new ArrayList<>();
        list.forEach(item -> {
            TicketOrderDetailsDto dto = new TicketOrderDetailsDto();
            BeanUtil.copyNotNullProperties(dto, item);
            String statusStr = "";
            if (OrderStatus.NEW.getCode().equals(item.getStatus())) {
                statusStr = "待支付";
            } else if (OrderStatus.SUCCESS.getCode().equals(item.getStatus())) {
                statusStr = "报名成功";
            } else {
                statusStr = "报名失败";
            }
            dto.setStatusStr(statusStr);
            String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item.getSaveTime());
            dto.setSaveTime(dateStr);
            dto.setRelateTicketArr(ticketService.toName(item.getRelateTicketArr()));
            copyList.add(dto);
        });

        // 执行导出
        String fileName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "购票清单" + ".xls";
        ServletUtil su = new ServletUtil(fileName, req, resp);
        su.poiExcelServlet();
        String[] heads = {"序号", "订单号", "展区", "人数", "姓名", "联系电话", "下单时间", "订单状态", "实付金额"};
        String[] cols = {"id", "orderNo", "relateTicketArr", "quantity", "name", "phone", "saveTime", "statusStr", "totalPrice"};
        // 这里传第几个字段是数字，从0开始
        int[] numerics = {0, 3, 5};
        ServletUtil suResp = new ServletUtil(resp);
        PoiExcelExport<CoursesOrder> pee = new PoiExcelExport(fileName, heads, cols, copyList, numerics, suResp.getOut());
        pee.exportExcel();
    }

}
